package com.homework.hugh.controller;

import com.homework.hugh.cache.GuavaService;
import com.homework.hugh.entity.TokenInfo;
import com.homework.hugh.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: Hugh
 * @Date: 2020/10/26
 */
@RestController
@RequestMapping("/api/user")
public class LoginController {

    @Autowired
    private GuavaService guavaService;

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email 邮箱
     * @param password 密码
     * @return 邮箱地址
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email, @PathVariable String password, HttpServletRequest request, HttpServletResponse response){
        Object o = guavaService.get(Constant.token_key_pre + email);
        if(Objects.isNull(o)){
            return "false";
        }
        TokenInfo tokenInfo;
        if(o instanceof TokenInfo){
            tokenInfo = (TokenInfo)o;
        }else{
            return "false";
        }

        Boolean agree = (email + password).equals(tokenInfo.getToken());
        if(agree){
            Cookie cookie = new Cookie("login_token", tokenInfo.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            Cookie emailCookie = new Cookie("login_email", tokenInfo.getEmail());
            emailCookie.setPath("/");
            response.addCookie(emailCookie);
            //跳转到欢迎界面s
            return "true";
        }
        return "false";
    }

}
